package com.labbit.platform.commons.exception;


import com.labbit.platform.commons.exception.message.ExceptionMessage;
import org.slf4j.helpers.MessageFormatter;

/**
 * 业务异常
 *
 * @author ChenYu
 * @date 2017/12/13 14:49
 */
public class BusinessException extends RuntimeException {

    private ExceptionMessage exceptionMessage;

    public BusinessException(ExceptionMessage message) {
        super(message.getMessage());
        this.exceptionMessage = message;
    }

    public BusinessException(ExceptionMessage message, Throwable cause) {
        super(message.getMessage(), cause);
        this.exceptionMessage = message;
    }

    public ExceptionMessage getExceptionMessage() {
        return exceptionMessage;
    }

    /**
     * 获取业务异常对象
     */
    public static BusinessException getInstance(String message, Integer code) {
        return new BusinessException(new ExceptionMessage() {
            @Override
            public String getMessage() {
                return message;
            }

            @Override
            public int getCode() {
                return code;
            }
        });
    }

    public static ExceptionMessage createMessage(ExceptionMessage message, Object... data) {
        ExceptionMessage newMessage = new ExceptionMessage() {
            @Override
            public String getMessage() {
                return MessageFormatter.arrayFormat(message.getMessage(), data).getMessage();
            }

            @Override
            public int getCode() {
                return message.getCode();
            }
        };
        return newMessage;
    }
}
